package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配
    private final AntPathMatcher matcher = new AntPathMatcher();

    //静态  拦截器路径
    private static final String[] not_check_url = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/user/sendMsg",
            "/user/login"
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        //强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求路径
        String url = request.getRequestURI();

        //判断是否要处理
        boolean check = checkUrl(url);

        //check = false 不用处理
        // !check 用处理
        //判断改路径是否要处理
        if (!check){
            filterChain.doFilter(request,response);
            return;//方法为void  但是表示退出
        }

        //判断是否登录了已经  登录的不用处理
        if (request.getSession().getAttribute("employee") != null ){

            //获取当前登录用户ID  存入ThreadLocal中
            Long currentId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(currentId);

            //放行
            filterChain.doFilter(request,response);

            //放行后 放置内存爆满  所有要删除用户ID
            BaseContext.removeCurrentId();
            return;
        }

        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }
        //运行到此处则表示条件都不通过  要跳转到登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }


    //判断是否要处理
    //false 不用处理
    private boolean checkUrl(String url) {
        for (String notcheck : not_check_url) {
            if (matcher.match(notcheck,url)){
                //判断对 表示不用处理
                return false;
            }
        }
        return true;
    }
}
